<script setup lang="ts">
	import { computed, ref, unref } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { route } from '@/uni_modules/uview-plus'
	import { useLocation } from '@/hooks/web/useLocation'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { useUserStore } from '@/stores/user'
	import { getListApi, returnOrderList } from '@/package_tms/api/Home'

	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const { getLocation } = useLocation()

	onShow(() => {
		paging.value?.reload()
	})

	const useTabs = () => {
		const currentIndex = ref(0)

		const tabsColumns = computed(() => {
			return [
				{
					name: '配送单',
					badge: { value: taskInfo.value.undone },
					id: 1
				},
				{
					name: '已签收',
					badge: { value: taskInfo.value.done },
					id: 2
				},
				{
					name: '回库单',
					badge: { value: taskInfo.value.undone_refund },
					id: 3
				}
			]
		})

		const taskInfo = ref({
			undone: 0,
			done: 0,
			undone_refund: 0
		})

		const currentTabsItem = computed(() => {
			return unref(tabsColumns)[unref(currentIndex)]
		})

		return {
			currentIndex,
			tabsColumns,
			currentTabsItem,
			taskInfo
		}
	}
	const { tabsColumns, currentIndex, taskInfo, currentTabsItem } = useTabs()

	const paging = ref<ZPagingInstance>()
	const useCURD = () => {
		const dataList = ref([])
		const query = ref({
			store_name: '',
			lon: '', // 经度
			lat: '', // 纬度
		})

		const getList : ZPagingEvent.Query = async (page, limit) => {
			try {
				const locationData = await getLocation();
				query.value.lat = locationData.latitude || ''
				query.value.lon = locationData.longitude || ''
				const params = { page, limit, order_status: unref(currentTabsItem).id, ...query.value }
				try {
					const res = await getListApi(params)
					taskInfo.value.done = res.data.total_done
					taskInfo.value.undone = res.data.total_undone
					taskInfo.value.undone_refund = res.data.total_undone_refund
					paging.value?.complete([...res.data.list])
				} catch (err) {
					showNotify({
						type: 'error',
						message: err.msg
					})
					paging.value?.complete(false)
				}
			} catch (err) {
				showNotify({
					type: 'error',
					message: '获取位置信息失败，请检查定位权限'
				})
			}
		}

		const searchAction = () => {
			paging.value?.reload()
		}

		return {
			dataList,
			getList,
			searchAction,
			query
		}
	}
	const { dataList, getList, searchAction, query } = useCURD()

	// 导航
	const openLocation = (item) => {
		uni.openLocation({
			latitude: Number(item.lat),
			longitude: Number(item.lon),
			name: item.address
		})
	}

	// 距离格式化
	const formatDistance = (distance : number | string) => {
		if (typeof distance === 'string') {
			return distance;
		}
		if (Number(distance) < 1000) {
			return `${distance} m`;
		} else {
			return `${(distance / 1000).toFixed(2)} km`;
		}
	};

	// 电话
	const callStore = (phoneNumber : string) => {
		uni.makePhoneCall({
			phoneNumber
		})
	}

	// 查看订单
	const toStoreDetail = (item) => {
		route({
			url: 'package_tms/pages/Detail/index',
			params: {
				store_id: item.store_id,
				store: item.store,
				order_status: unref(currentTabsItem).id
			}
		})
	}
	// 送货地图
	const toPage = () => {
		uni.setStorageSync('storeList', JSON.stringify(dataList.value));
		route({
			url: 'package_tms/pages/Map/index'
		})
	}
	// tabs切换
	const onSearch = () => {
		query.value.store_name = ''
		paging.value?.reload()

	}
	// 返回
	const leftClick = () => {
		uni.reLaunch({
			url: `/pages/Workbench/index`
		})
	}
	// 手机物理返回
	const isShow = ref(true)
	const beforeleave = () => {
		isShow.value = false
		uni.reLaunch({
			url: `/pages/Workbench/index`
		})
	}
</script>

<template>
	<up-navbar title="送货签收" placeholder @leftClick="leftClick"></up-navbar>
	<view v-if="isShow">
		<page-container :show="isShow" :overlay="false" @beforeleave="beforeleave"></page-container>
	</view>
	<view class="content">
		<view class="user_info_wrap">
			<view class="search-wrap">
				<up-search v-model="query.store_name" @search="searchAction" @custom="searchAction" @clear="searchAction"
					showAction actionText="搜索" animation shape="square" bgColor="rgba(243, 242, 245, 1)"></up-search>
			</view>
			<view class="user-info">
				<view class="avatar-wrap">
					<up-tabs v-model:current="currentIndex" @change="onSearch" :list="tabsColumns"
						:itemStyle="{ height: '104rpx', fontSize: '28rpx' }"
						:activeStyle="{ color: 'rgba(54, 116, 242, 1)' }" lineWidth="104rpx"
						lineColor=" rgba(54, 116, 242, 1)">
					</up-tabs>
				</view>
				<view class="ditu" @click="toPage()" v-if="currentIndex == 0 && dataList.length > 0">
					<view class="ditu-img">
						<image style="width: 40rpx;height: 40rpx;" src="/package_tms/static/icon/icon2.png"></image>
					</view>
					<text class="ditu-name">送货地图</text>
				</view>
			</view>

		</view>
		<view class="main">
			<z-paging ref="paging" v-model="dataList" @query="getList" :fixed="false" height="calc(100vh - 400rpx)">
				<view class="main-box" v-for="(item,index) in dataList" :key="index">
					<view class="main-header">
						<view class="header-name">{{item.store}}<span @click="callStore(item.phone)"
								style="font-weight: 500;color: rgba(100, 101, 102, 1);margin-left: 20rpx;"
								v-if="item.phone">({{item.phone}})</span>
						</view>
						<view class="header-right" @click="openLocation(item)">
							<view class="right-img">
								<image style="width: 40rpx;height: 40rpx;" src="/package_tms/static/icon/icon3.png">
								</image>
							</view>
							<text class="right-name">导航去此处</text>
						</view>
					</view>
					<view class="mian-address">
						<view class="address-name">{{item.address}}</view>
						<view class="distance-name">{{formatDistance(item.distance)}}</view>
					</view>
					<view class="dd-box">
						<view class="dd">
							<view class="dd-img">
								<image style="width: 40rpx;height: 40rpx;" src="/package_tms/static/icon/icon4.png">
								</image>
							</view>
							<text class="dd-name">订单：</text>
							<text style="font-weight: 700;color: rgba(245, 99, 81, 1);">{{item?.order_num}}</text>
						</view>
						<view class="dd">
							<view class="dd-img">
								<image style="width: 40rpx;height: 40rpx;" src="/package_tms/static/icon/icon5.png">
								</image>
							</view>
							<text class="dd-name">金额：</text>
							<text
								style="font-weight: 700;color: rgba(245, 99, 81, 1);">￥{{item?.order_amount || '暂无'}}</text>
						</view>
						<!-- <view class="dd" v-if="currentIndex == 1">
							<view class="dd-img">
								<image style="width: 40rpx;height: 40rpx;" src="/package_tms/static/icon/icon1.png">
								</image>
							</view>
							<text class="dd-name">配送收益：</text>
							<text style="font-weight: 700;color: rgba(245, 99, 81, 1);">￥{{item?.driver_money}}</text>
						</view> -->
					</view>
					<view style="margin-top: 40rpx;">
						<up-button text="查看订单" shape="circle" @click="toStoreDetail(item)"
							color="rgba(55, 131, 252, 1)"></up-button>
					</view>
				</view>
			</z-paging>
		</view>
		<up-notify ref="NotifyRef"></up-notify>
	</view>
</template>

<style scoped lang="scss">
	.content {
		width: 100%;
		background: rgba(242, 243, 245, 1);
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS 11.2及以上 */

	}

	.user_info_wrap {
		@include flex();
		flex-direction: column;
		justify-content: flex-end;
		gap: 20rpx;
		width: 100%;
		height: 209rpx;
		background-color: #FFFFFF;
		padding: 0 26rpx 0rpx;
		box-sizing: border-box;

		.search-wrap {
			display: flex;
			align-items: center;
			width: 100%;
			height: 64rpx;
			border-radius: 20rpx;
			padding: 10rpx;
			background: rgba(243, 242, 245, 1);
		}

		.user-info {
			display: flex;
			justify-content: space-between;

			.ditu {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 170rpx;
				height: 68rpx;
				border-radius: 718rpx;
				border: 2rpx solid rgba(54, 116, 242, 1);
				margin-top: 20rpx;

				.ditu-img {
					width: 40rpx;
					height: 40rpx;
					vertical-align: middle;
					margin-right: 10rpx;
				}

				.ditu-name {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(54, 116, 242, 1);
				}
			}

		}


	}

	.main {
		width: 100%;
		// height: calc(100vh - 249rpx);
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS 11.2及以上 */

		.main-box {
			width: 702rpx;
			// height: 448rpx;
			border-radius: 12rpx;
			background: rgba(255, 255, 255, 1);
			padding: 30rpx;
			box-sizing: border-box;
			margin: 20rpx auto;

			.main-header {
				display: flex;
				justify-content: space-between;

				.header-name {
					font-size: 28rpx;
					font-weight: 700;
					color: rgba(2, 14, 36, 1);
				}

				.header-right {
					display: flex;

					.right-img {
						width: 34rpx;
						height: 34rpx;
						vertical-align: middle;
						margin-right: 20rpx;
					}

					.right-name {
						font-size: 28rpx;
						font-weight: 700;
						color: rgba(55, 131, 252, 1);
					}
				}
			}

			.mian-address {
				display: flex;
				justify-content: space-between;
				margin-top: 20rpx;

				.address-name {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(100, 101, 102, 1);
				}

				.distance-name {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(156, 154, 161, 1);
				}
			}

			.dd-box {
				width: 654rpx;
				// height: 148rpx;
				border-radius: 6rpx;
				margin-top: 40rpx;
				padding: 30rpx;
				box-sizing: border-box;
				background: linear-gradient(180deg, rgba(242, 243, 245, 1) 0%, rgba(242, 243, 245, 0) 100%);

				.dd {
					display: flex;
					margin-bottom: 20rpx;

					.dd-img {
						width: 40rpx;
						height: 40rpx;
						vertical-align: middle;
						margin-right: 20rpx;
					}

					.dd-name {
						font-size: 28rpx;
						font-weight: 500;
						color: rgba(100, 101, 102, 1);
					}
				}
			}
		}
	}
</style>